/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dpy.appmvdpy.Controllers;

import com.dpy.appmvdpy.Facades.UsersFacade;
import com.dpy.appmvdpy.Models.AlteraSenha;
import com.dpy.appmvdpy.Models.DefaultModel;
import com.dpy.appmvdpy.Models.Users;
import com.dpy.appmvdpy.Models.Validators.AlteraSenhaValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;


/**
 *
 * @author ac_psoares
 */
@Controller
@RequestMapping("/alteraSenha")
@PreAuthorize("hasRole('ROLE_USER')")
public class AlteraSenhaController {

    @Autowired
    public AlteraSenhaValidator validator;
    
    @Autowired
    public UsersFacade facade;
    
    @RequestMapping(value="/index", method=RequestMethod.GET)
    public ModelAndView alteraSenha()
    {
        AlteraSenha altera = new AlteraSenha();
        ModelAndView view = new ModelAndView("/alteraSenha/index");
        view.addObject("model",altera);
        return view;      
    }
    
    @RequestMapping(value="/index", method=RequestMethod.POST)
    public String  perform(@ModelAttribute("model")AlteraSenha model, BindingResult result, SessionStatus status)
    {
          validator.validate(model, result);
	  if (result.hasErrors())
	  {  
	     return "/alteraSenha/index";
	  }
          
          User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	  Users users = facade.getByUsername(user.getUsername());
          users.setPassword(model.getNovaSenha());
          facade.edit(users);
          
	  status.setComplete();
	  return "redirect:/pedidos/list";
    }
 
}
